package com.pf.common.annotation.validator;

import com.google.common.collect.Lists;
import com.pf.common.annotation.ExcelCheckDate;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * excel 日期格式校验
 *
 * @author PanFei
 * @version 1.0.0
 * @createTime 2022/11/27 16:31
 */
public class ExcelCheckDateValidator implements ConstraintValidator<ExcelCheckDate, String> {
    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        List<String> datePatternList = Lists.newArrayList("yyyy-MM-dd", "yyyy/MM/dd", "yyyyMMdd", "yyyy MM dd");
        boolean match;
        for (String datePattern : datePatternList) {
            SimpleDateFormat sdf = new SimpleDateFormat(datePattern);
            try {
                sdf.parse(value);
                match = true;
            } catch (Exception e) {
//                e.printStackTrace();
                match = false;
            }

            if (match) {
                return true;
            }
        }
        return false;
    }
}
